const Router = require('koa-router')
const router = new Router({
  prefix: '/pinduoduo'
})
const fs = require('fs')
const path = require('path')
const request = require('request')
// const xlsx = require('node-xlsx')
const root = path.join( __dirname,  '../');
const imageMagick = require('gm').subClass({ imageMagick : true })
// const uploadPath = path.join( __dirname,  `../public/img/tmall/`);
const uploadPath = path.join(`D:/天猫图/`);

// 检查目录是否存在，不存在则创建
let mkdirs = ( dirname, callback=()=>{} )=> {
  fs.exists(dirname, function(exists) {
    if (exists) {
      callback();
    } else {
      mkdirs(path.dirname(dirname), function() {
        fs.mkdir(dirname, callback);
      });
    }
  });
};

// 上传前台传来的图片地址
let upload = (path, pics, type) => {
  return new Promise((resolve, reject) => {
    mkdirs(path, () => {
      let i = 0;
      for(let k in pics){
        let src = pics[k];
        // src可能是一个对象{name, src}，或是一个字符串类型的图片地址
        const isObject = src instanceof Object;
        if(isObject){
          const picInfo = src;
          let ext = picInfo.src.slice(picInfo.src.lastIndexOf('.') + 1);
          fileName = `${picInfo.name}.${ext}`;
          
          try{
            request(picInfo.src).pipe(fs.createWriteStream(path + fileName));
            if(type == 'is800'){
              imageMagick(request(picInfo.src))
              .resize(800,800,'!')
              .write(path+fileName, err=>{
                if(err) console.log(err)
              })
            }else{
              request(picInfo.src).pipe(fs.createWriteStream(path + fileName));
            }
          }catch(err){
            console.log(err)
            reject(err);
          }
        }else{
          let fileName = `${i+1}.${src.slice(src.lastIndexOf('.') + 1)}`;
          
          try{
            request(src).pipe(fs.createWriteStream(path + fileName));
            if(type == 'is800'){
              imageMagick(request(src))
              .resize(800, 800)
              .in("-gravity", "center")
              .extent(800, 800)
              .write(path+fileName, err=>{
                if(err) console.log(err)
              })
            }else{
              request(src).pipe(fs.createWriteStream(path + fileName));
            }
          }catch(err){
            reject(err);
          }
        }
        i++;
      }
      resolve();
    });
  })
};

router.get('/', (ctx, next) => {
  ctx.body = 'Hi, Pinduoduo!'
})

// 上传天猫图片
router.post('/tmallPics', async (ctx, next) => {
  const { name, mainPics, catePics, detailPics, material, brand, model, style, title } = ctx.request.body;
  const mainDir = `${name}/main/`;
  const cateDir = `${name}/cates/`;
  const detailDir = `${name}/detail/`;

  // 保存商品属性信息到Execl表格
//   const xlsxPath = path.join(root + 'data-铠甲.xlsx');
//   const sheet1 = xlsx.parse(xlsxPath)[0].data;
//   const modelsFromName = name.split(/[\\\/]/).pop().split(',');
//   const sheetData = [
//     ...sheet1,
//     [
//       brand,
//       modelsFromName.map(v=>`${v}/${v}【送钢化膜】`).join('/'),
//       `${brand}${model}手机壳女防摔网红磨砂全包边可爱新款opop男0pp0手机套韩版个性潮流`,
//       '炫酷黑/海军蓝/炫酷红',
//       '【指环支架款】无赠品/【指环支架款】送挂绳/【隐形支架款】无赠品/【隐形支架款】送挂绳',
//       `${modelsFromName.map(v=>12.8 + '/' + 15.8).join('/')}|1/2/0/1`,
//       '亚克力',
//       '保护壳',
//       '磨砂/磁吸',
//       `【关于手机型号】打开手机设置-关于本机，即可查看手机型号。
// 【关于发货】本店仅支持中通快递，广东深圳发货，16点前下单当天发货，省内1~2天送达，省外3~4天，偏远地区5~7天。
// 【优先发货】收藏店铺和商品优先发货哦！`,
//       path.resolve(uploadPath + name + '/')
//     ],
//   ]
//   function writeXls(datas) {
//     var buffer = xlsx.build([
//         {
//             name:'Sheet1',
//             data:datas   
//         }
//     ]);
//     fs.writeFileSync(xlsxPath, buffer, {'flag':'w'});
//   }
//   try{
//     writeXls(sheetData)
//   }catch(err){
//     return ctx.body = {
//       status: 'fail',
//       errMsg: '表格数据保存失败，请确保表格窗口已关闭。',
//       data: {}
//     };
//   }

  await upload(uploadPath + mainDir, mainPics, 'is800').catch(()=>{
    ctx.body = {
      status: 'fail',
      errMsg: '主图保存失败',
      data: {}
    };
  });
  await upload(uploadPath + cateDir, catePics, 'is800').catch(()=>{
    ctx.body = {
      status: 'fail',
      errMsg: '分类图保存失败',
      data: {}
    };
  });
  await upload(uploadPath + detailDir, detailPics).catch(()=>{
    ctx.body = {
      status: 'fail',
      errMsg: '详情图保存失败',
      data: {}
    };
  })

  ctx.body = {
    status: 'success',
    data: {
      path: uploadPath
    }
  };
})

// 上传单张正方形主图
router.post('/singleMain', async(ctx, next) => {
  const { src, dir } = ctx.request.body;
  const path = uploadPath + dir + '/';
  await upload(path, [src])
  .then(()=>{
    ctx.body = {
      status: 'success',
      data: {
        path: path
      }
    }
  })
  .catch(err=>{
    console.log(err)
    ctx.body = {
      status: 'fail',
      errMsg: '主图保存失败',
      data: {}
    };
  })
})

module.exports = router;